package com.guanjia.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.guanjia.entity.CrowdFunding;
import com.guanjia.entity.User;
import com.guanjia.entity.vo.CrowdUserInfVo;
import com.guanjia.service.CrowdFundingService;
import com.guanjia.service.impl.CrowdFundingServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.SimpleFormatter;

@Controller
@RequestMapping("/zhongchou")
public class CrowdFundingController{
    @Autowired
    private CrowdFundingService crowdFundingService;


    //只需要加上下面这段即可，注意不能忘记注解
    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {

        //转换日期
        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器
    }



    /*
    * 跳转至众筹表单界面
    * */
    @RequestMapping("/form")
    public String CrowdFundingForm(){
        return "cfgj/zhongchou_form";
    }

    @RequestMapping("/formSu")
    public String  CrowdFundingFormSu(){return "cfgj/zhongchou_formsucess";}

    @RequestMapping("/save")
    public String CrowdFundingSave(HttpServletRequest request, HttpSession session) throws IOException {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String projectname=request.getParameter("projectname");
        String faceto=request.getParameter("faceto");
        String money=request.getParameter("money");
        Date starttime=null;
        Date endtime=null;
        try {
            starttime= format.parse(request.getParameter("starttime"));
            endtime= format.parse(request.getParameter("endtime"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        User user=(User) session.getAttribute("user");
        String projectabstract=request.getParameter("projectabstract");
        String edit=request.getParameter("edit");
        String newfileName="";
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request))
        {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
            //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();

            while(iter.hasNext())
            {
                //一次遍历所有文件
                MultipartFile file=multiRequest.getFile(iter.next().toString());
                if(file!=null)
                {
                    String fileName=file.getOriginalFilename();
                    String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                    newfileName=UUID.randomUUID().toString() +"."+suffix;
                    //获取文件名
                    String filePath = "F:/picall/cfgj/"+user.getTell()+"/zongchoupic/" ;
                    //自定义上传路径
                    File files = new File(filePath,newfileName);
                    if(!files.exists()){//判断文件夹是否存在，如果不存在则创建
                        if(!files.getParentFile().exists()){
                            files.getParentFile().mkdirs();
                        }
                        files.createNewFile();
                    }
                    file.transferTo(files);//上传文件

                    //上传
                    // file.transferTo(new File(path));
                }

            }

        }


        CrowdFunding crowdFunding=new CrowdFunding(user.getId(),Double.valueOf(money),projectname,faceto,starttime,endtime,projectabstract,edit,user.getTell()+"/zongchoupic/"+newfileName);
        crowdFundingService.insertForm(crowdFunding);
        System.out.println(crowdFunding);
        return "redirect:/zhongchou/formSu";
    }

    @RequestMapping("/list")
    public String CrowdFundingList(Model model){
        List<CrowdFunding> handlist = crowdFundingService.handList();
        List<CrowdFunding> newList = crowdFundingService.newList();
        model.addAttribute("crows",handlist);
        model.addAttribute("newcrows",newList);
        return "cfgj/zhongchouMain";
    }

    @RequestMapping("/mainInf")
    public String mainInf(int id,Model model){
        CrowdFunding crowdFunding=crowdFundingService.findCrowdById(id);
        CrowdUserInfVo crowdUserInfVo=crowdFundingService.findCrowdUser(crowdFunding.getUserId());
        model.addAttribute("crowd",crowdFunding);
        model.addAttribute("crowdUser",crowdUserInfVo);
         System.out.println(crowdFunding);
          System.out.println(crowdUserInfVo);
        return "cfgj/zhongchou_MainInfo";
    }
    @RequestMapping("/input")
    public  String inputZCmoney (){
        return "cfgj/inputzcmoney";
    }

    @RequestMapping("/mainList")
    public String showList(){return "cfgj/zhongchou_list";}

    @RequestMapping("/getlistData")
    @ResponseBody
    public Map<String,Object> touziLsit(Model model, Integer page, Integer size, String sort, String pname, Integer max, Integer min){
        Map<String,Object> map = new HashMap<>();
        IPage<CrowdFunding> list = crowdFundingService.showList(page,size,sort,pname,max,min);
        if (sort!=null&&sort.equals("1")){
            map.put("sort","1");
        }
        map.put("pname",pname);
        map.put("max",max);
        map.put("min",min);
        map.put("data",list.getRecords());
        map.put("count",list.getTotal());
        return map;
    }

}
